package cn.zhqr.common.util.str;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by yantingjun on 2018/12/4.
 */
public class RegexUtils {
    private static final Map<String,Pattern> pattern_cache = new HashMap<>();

    private static final Pattern number_pattern = Pattern.compile("[0-9]+");
    public static boolean test(String source,String regex){
        Pattern pattern = pattern_cache.get(regex);
        if(pattern == null){
            pattern = Pattern.compile(regex);
            pattern_cache.put(regex,pattern);
        }
        Matcher matcher = pattern.matcher(source);
        return matcher.matches();
    }

    public static String getContent(String source,String regex){
        return getContent(source, regex,0);
    }

    public static String getContent(String source,String regex,int group){
        Pattern pattern = pattern_cache.get(regex);
        if(pattern == null){
            pattern = Pattern.compile(regex);
            pattern_cache.put(regex,pattern);
        }
        Matcher matcher = pattern.matcher(source);
        if(matcher.find()){
            return matcher.group(group);
        }
        return null;
    }

    public static String getContent(String source,String regex,int group,int flags){
        Pattern pattern = pattern_cache.get(regex+"-"+flags);
        if(pattern == null){
            pattern = Pattern.compile(regex,flags);
            pattern_cache.put(regex+"-"+flags,pattern);
        }
        Matcher matcher = pattern.matcher(source);
        if(matcher.find()){
            return matcher.group(group);
        }
        return null;
    }

    public static List findNumbers(String str){
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotBlank(str)){
            Matcher matcher = number_pattern.matcher(str);
            while(matcher.find()){
                list.add(matcher.group());
            }
        }
        return list;
    }
    public static List findNumbers(String str,int digit){
        List<String> list = new ArrayList<>();
        if(StringUtils.isNotBlank(str)){
            Pattern pattern = Pattern.compile("[0-9]{"+digit+"}");
            Matcher matcher = pattern.matcher(str);
            while(matcher.find()){
                list.add(matcher.group());
            }
        }
        return list;
    }

    public static void main(String[] args) {
        String content = getContent("multipart/form-data;charset=ISO-8859-1",
                "charset\\s*=\\s*(\\S+)",1,Pattern.CASE_INSENSITIVE);
        System.out.println(content);
    }
}
